import React, { useState, useEffect } from 'react';
import { Card, Typography, Button, Spin, Alert, Space, Row, Col, Divider, Badge, Tag, Avatar } from 'antd';
import { QRCode } from 'antd';
import { LinkOutlined, DisconnectOutlined, ReloadOutlined, UserOutlined, CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons';
import { useAuth } from '../context/AuthContext';
import api from '../services/api';
import socketService from '../services/socket';

const { Title, Paragraph, Text } = Typography;

const WhatsAppConnect = () => {
  const { user } = useAuth();
  const [loading, setLoading] = useState(false);
  const [status, setStatus] = useState('disconnected');
  const [qrCode, setQrCode] = useState(null);
  const [message, setMessage] = useState('');
  const [error, setError] = useState('');
  const [sessionInfo, setSessionInfo] = useState(null);
  const [deviceInfo, setDeviceInfo] = useState(null);

  // 获取用户专属的WhatsApp连接状态
  const fetchStatus = async () => {
    try {
      setLoading(true);
      setError('');
      
      const response = await api.get(`/whatsapp/user/${user.id}/status`);
      
      if (response.data) {
        setStatus(response.data.status);
        setSessionInfo(response.data.sessionInfo);
        setDeviceInfo(response.data.deviceInfo);
        if (response.data.qrCode) {
          setQrCode(response.data.qrCode);
        }
        setMessage(response.data.message || '');
      }
    } catch (err) {
      console.error('获取用户WhatsApp状态失败:', err);
      setError(err.response?.data?.message || '获取状态失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取用户专属的二维码
  const fetchQRCode = async (retryCount = 0, maxRetries = 3) => {
    try {
      setLoading(true);
      setError('');
      
      console.log(`用户 ${user.username} 尝试获取二维码 (尝试 ${retryCount + 1}/${maxRetries + 1})...`);
      
      const response = await api.get(`/whatsapp/user/${user.id}/qrcode`);
      
      if (response.data && response.data.qrCode) {
        setQrCode(response.data.qrCode);
        setStatus('connecting');
        setMessage('请使用您的WhatsApp扫描专属二维码');
        console.log(`用户 ${user.username} 二维码获取成功`);
      } else {
        setError('获取二维码失败，服务可能未初始化');
        if (retryCount < maxRetries) {
          console.log(`等待5秒后重试获取二维码... (${retryCount + 1}/${maxRetries})`);
          setTimeout(() => fetchQRCode(retryCount + 1, maxRetries), 5000);
        }
      }
    } catch (err) {
      console.error('获取二维码错误:', err);
      if (err.response?.status === 404) {
        setError('WhatsApp服务未就绪或未初始化，请尝试"初始化我的WhatsApp连接"按钮');
        setStatus('error');
      } else {
        setError(err.response?.data?.message || '获取二维码失败');
      }
      
      if (err.response?.status === 404 && retryCount < maxRetries) {
        console.log(`等待5秒后重试获取二维码... (${retryCount + 1}/${maxRetries})`);
        setTimeout(() => fetchQRCode(retryCount + 1, maxRetries), 5000);
      }
    } finally {
      setLoading(false);
    }
  };

  // 断开用户的WhatsApp连接
  const disconnect = async () => {
    try {
      setLoading(true);
      setError('');
      
      const response = await api.post(`/whatsapp/user/${user.id}/disconnect`);
      
      if (response.data && response.data.success) {
        setStatus('disconnected');
        setQrCode(null);
        setSessionInfo(null);
        setDeviceInfo(null);
        setMessage(response.data.message || '已断开连接');
      } else {
        setError(response.data?.message || '断开连接失败');
      }
    } catch (err) {
      setError(err.response?.data?.message || '断开连接失败');
    } finally {
      setLoading(false);
    }
  };

  // 初始化用户专属的WhatsApp服务
  const initializeUserWhatsApp = async () => {
    try {
      setLoading(true);
      setError('');
      setMessage(`正在为用户 ${user.username} 初始化WhatsApp服务，请稍候...`);
      
      // 先断开现有连接
      try {
        await api.post(`/whatsapp/user/${user.id}/disconnect`);
        console.log(`用户 ${user.username} 已断开现有连接`);
      } catch (disconnectErr) {
        console.log('断开连接过程中出错或无现有连接:', disconnectErr);
      }
      
      console.log(`开始为用户 ${user.username} 初始化WhatsApp...`);
      
      try {
        const initResponse = await api.post(`/whatsapp/user/${user.id}/initialize`);
        
        console.log('初始化响应:', initResponse.data);
        
        if (initResponse.data.status && initResponse.data.status.status === 'connected') {
          setStatus('connected');
          setMessage('WhatsApp已成功连接');
          setSessionInfo(initResponse.data.sessionInfo);
          setLoading(false);
          return;
        }
        
        if (initResponse.data.status && initResponse.data.status.status === 'connecting') {
          setMessage('WhatsApp正在连接中，请等待...');
          setTimeout(() => fetchQRCode(0, 5), 2000);
          return;
        }
        
        setMessage(initResponse.data.message || '正在初始化WhatsApp服务，请稍候...');
        
        // 轮询检查状态
        let pollCount = 0;
        const maxPolls = 30;
        const pollInterval = 3000;
        
        const pollStatus = async () => {
          if (pollCount >= maxPolls) {
            setError('初始化超时，请重试');
            setLoading(false);
            return;
          }
          
          pollCount++;
          
          try {
            const statusResponse = await api.get(`/whatsapp/user/${user.id}/status`);
            console.log(`用户 ${user.username} 状态轮询 ${pollCount}/${maxPolls}:`, statusResponse.data);
            
            if (statusResponse.data.status === 'connected') {
              setStatus('connected');
              setMessage('WhatsApp已成功连接');
              setSessionInfo(statusResponse.data.sessionInfo);
              setDeviceInfo(statusResponse.data.deviceInfo);
              setQrCode(null);
              setLoading(false);
            } else if (statusResponse.data.status === 'connecting' && statusResponse.data.qrCode) {
              setQrCode(statusResponse.data.qrCode);
              setStatus('connecting');
              setMessage('请使用您的WhatsApp扫描专属二维码');
              setLoading(false);
            } else if (statusResponse.data.status === 'disconnected') {
              setTimeout(pollStatus, pollInterval);
            } else {
              setTimeout(pollStatus, pollInterval);
            }
          } catch (error) {
            console.error('轮询状态失败:', error);
            setTimeout(pollStatus, pollInterval);
          }
        };
        
        setTimeout(pollStatus, 2000);
        
      } catch (err) {
        console.error(`用户 ${user.username} 重新初始化WhatsApp服务失败:`, err);
        
        let errorMessage = '初始化失败';
        
        if (err.response && err.response.data) {
          console.log('服务器返回的错误数据:', err.response.data);
          
          if (err.response.data.error) {
            errorMessage = `初始化错误: ${err.response.data.error}`;
            if (err.response.data.errorType) {
              errorMessage += ` (${err.response.data.errorType})`;
            }
          } else if (err.response.data.message) {
            errorMessage = err.response.data.message;
          }
        }
        
        if (err.code === 'ERR_NETWORK' || err.code === 'ERR_CONNECTION_RESET') {
          setError('网络连接错误，请检查后端服务是否正常运行');
        } else if (err.response?.status === 500) {
          setError(`服务器内部错误: ${errorMessage}`);
          setStatus('error');
        } else {
          setError('初始化WhatsApp服务失败: ' + errorMessage);
        }
        
        setLoading(false);
      }
    } catch (err) {
      console.error(`用户 ${user.username} 初始化WhatsApp服务失败:`, err);
      setError('初始化WhatsApp服务失败: ' + (err.response?.data?.message || err.message));
      setLoading(false);
    }
  };

  // 监听用户专属的WebSocket事件
  useEffect(() => {
    if (!user) return;
    
    const userId = user.id.toString();
    
    // 监听用户专属的二维码更新
    const handleQrCode = (data) => {
      if (data && data.qr && data.userId === userId) {
        setQrCode(data.qr);
        setStatus('connecting');
        setMessage('请使用您的WhatsApp扫描专属二维码');
      }
    };
    
    // 监听用户专属的状态更新
    const handleStatus = (data) => {
      if (data && data.userId === userId) {
        const prevStatus = status;
        setStatus(data.status);
        setMessage(data.message || '');
        setSessionInfo(data.sessionInfo);
        setDeviceInfo(data.deviceInfo);
        
        if (prevStatus !== 'connected' && data.status === 'connected') {
          setQrCode(null);
        }
      }
    };
    
    // 监听连接状态变化
    const handleConnectionState = (data) => {
      if (data && data.userId === userId) {
        console.log(`用户 ${user.username} 连接状态变化:`, data.state);
      }
    };
    
    socketService.onEvent(`whatsapp:qr:${userId}`, handleQrCode);
    socketService.onEvent(`whatsapp:status:${userId}`, handleStatus);
    socketService.onEvent(`whatsapp:connection_state:${userId}`, handleConnectionState);
    
    return () => {
      socketService.offEvent(`whatsapp:qr:${userId}`);
      socketService.offEvent(`whatsapp:status:${userId}`);
      socketService.offEvent(`whatsapp:connection_state:${userId}`);
    };
  }, [user, status]);

  // 组件加载时获取用户状态
  useEffect(() => {
    if (user) {
      fetchStatus();
    }
  }, [user]);

  // 渲染用户信息卡片
  const renderUserInfo = () => (
    <Card size="small" style={{ marginBottom: 16 }}>
      <Space>
        <Avatar icon={<UserOutlined />} />
        <div>
          <Text strong>{user?.fullName || user?.username}</Text>
          <br />
          <Text type="secondary">
            {user?.role === 'admin' ? '管理员' : '销售人员'} • 
            {status === 'connected' ? (
              <Badge status="success" text="已连接" />
            ) : status === 'connecting' ? (
              <Badge status="processing" text="连接中" />
            ) : (
              <Badge status="default" text="未连接" />
            )}
          </Text>
        </div>
      </Space>
    </Card>
  );

  // 渲染会话信息
  const renderSessionInfo = () => {
    if (!sessionInfo) return null;
    
    return (
      <Card size="small" title="连接信息" style={{ marginTop: 16 }}>
        <Row gutter={[16, 8]}>
          <Col span={12}>
            <Text type="secondary">手机号码:</Text>
            <br />
            <Text>{sessionInfo.phoneNumber || '未知'}</Text>
          </Col>
          <Col span={12}>
            <Text type="secondary">连接时间:</Text>
            <br />
            <Text>{sessionInfo.startTime ? new Date(sessionInfo.startTime).toLocaleString() : '未知'}</Text>
          </Col>
          {deviceInfo && (
            <>
              <Col span={12}>
                <Text type="secondary">设备类型:</Text>
                <br />
                <Text>{deviceInfo.deviceType || '未知'}</Text>
              </Col>
              <Col span={12}>
                <Text type="secondary">电池电量:</Text>
                <br />
                <Text>{deviceInfo.batteryLevel ? `${deviceInfo.batteryLevel}%` : '未知'}</Text>
              </Col>
            </>
          )}
        </Row>
      </Card>
    );
  };

  // 根据状态显示不同内容
  const renderContent = () => {
    if (loading) {
      return (
        <div style={{ textAlign: 'center', padding: '50px 0' }}>
          <Spin size="large" />
          <Paragraph style={{ marginTop: 16 }}>
            {message || `正在为用户 ${user?.username} 处理请求...`}
          </Paragraph>
        </div>
      );
    }

    if (status === 'connected') {
      return (
        <div style={{ textAlign: 'center', padding: '30px 0' }}>
          <CheckCircleOutlined style={{ fontSize: 64, color: '#52c41a' }} />
          <Title level={3} style={{ marginTop: 16, color: '#52c41a' }}>
            WhatsApp已连接
          </Title>
          <Paragraph>
            {message || `用户 ${user?.username} 的WhatsApp已成功连接，可以开始使用了。`}
          </Paragraph>
          
          {renderSessionInfo()}
          
          <Divider />
          
          <Space>
            <Button 
              type="primary" 
              danger 
              icon={<DisconnectOutlined />} 
              onClick={disconnect}
              loading={loading}
            >
              断开我的连接
            </Button>
            <Button 
              icon={<ReloadOutlined />} 
              onClick={fetchStatus}
            >
              刷新状态
            </Button>
          </Space>
        </div>
      );
    }

    if (status === 'connecting' && qrCode) {
      return (
        <div style={{ textAlign: 'center', padding: '20px 0' }}>
          <Title level={3}>请扫描您的专属二维码</Title>
          <Paragraph>
            打开手机WhatsApp，点击"设置" → "已连接的设备" → "连接设备"
          </Paragraph>
          <Tag color="blue" style={{ marginBottom: 16 }}>
            专属用户: {user?.username}
          </Tag>
          
          <div className="qr-container">
            <QRCode 
              value={qrCode} 
              size={250} 
              style={{ margin: '20px 0' }}
              status="active"
            />
            <Paragraph type="secondary">
              此二维码专属于用户 {user?.username}，请勿分享给他人
            </Paragraph>
          </div>
          
          <Space>
            <Button 
              type="primary" 
              icon={<ReloadOutlined />} 
              onClick={fetchQRCode}
              loading={loading}
            >
              刷新二维码
            </Button>
            <Button 
              danger 
              icon={<DisconnectOutlined />} 
              onClick={disconnect}
              loading={loading}
            >
              取消连接
            </Button>
          </Space>
        </div>
      );
    }

    if (status === 'error') {
      return (
        <div style={{ textAlign: 'center', padding: '30px 0' }}>
          <CloseCircleOutlined style={{ fontSize: 64, color: '#ff4d4f' }} />
          <Title level={3} style={{ marginTop: 16, color: '#ff4d4f' }}>
            WhatsApp服务未就绪
          </Title>
          <Paragraph>
            {message || `用户 ${user?.username} 的WhatsApp服务未正确初始化，请检查环境配置。`}
          </Paragraph>
          <Alert
            message="初始化错误 - 需要网络代理"
            description={
              <div>
                <p><strong>重要提示：WhatsApp在中国大陆无法直接访问，需要设置代理</strong></p>
                <ol>
                  <li>由于网络限制，您需要先启动代理软件（如Clash、V2Ray等）</li>
                  <li>确保代理运行在以下端口之一：
                    <ul>
                      <li>Socks5代理: 127.0.0.1:10808</li>
                      <li>HTTP代理: 127.0.0.1:10809</li>
                    </ul>
                  </li>
                  <li>如果您的代理端口不同，请联系管理员修改后端配置文件</li>
                  <li>代理设置完成后，点击下方按钮重新初始化</li>
                </ol>
              </div>
            }
            type="error"
            showIcon
            style={{ marginTop: 16, textAlign: 'left' }}
          />
          <Space style={{ marginTop: 16 }}>
            <Button 
              type="primary" 
              icon={<ReloadOutlined />} 
              onClick={initializeUserWhatsApp}
              loading={loading}
            >
              初始化我的WhatsApp连接
            </Button>
            <Button
              onClick={() => window.open('https://web.whatsapp.com', '_blank')}
              icon={<LinkOutlined />}
            >
              前往WhatsApp Web官方
            </Button>
          </Space>
        </div>
      );
    }

    return (
      <div style={{ textAlign: 'center', padding: '30px 0' }}>
        <CloseCircleOutlined style={{ fontSize: 64, color: '#ff4d4f' }} />
        <Title level={3} style={{ marginTop: 16, color: '#ff4d4f' }}>
          WhatsApp未连接
        </Title>
        <Paragraph>
          {message || `用户 ${user?.username} 需要扫描专属二维码以连接WhatsApp。`}
        </Paragraph>
        
        <Button 
          type="primary" 
          icon={<LinkOutlined />} 
          onClick={fetchQRCode}
          loading={loading}
          style={{ marginTop: 16 }}
        >
          连接我的WhatsApp
        </Button>
      </div>
    );
  };

  if (!user) {
    return (
      <Card title="WhatsApp连接">
        <Alert message="用户信息加载中..." type="info" />
      </Card>
    );
  }

  return (
    <Card title="WhatsApp连接管理" variant="default">
      {renderUserInfo()}
      
      {error && <Alert message={error} type="error" showIcon style={{ marginBottom: 16 }} />}
      
      <Row justify="center">
        <Col xs={24} sm={24} md={20} lg={16} xl={14}>
          {renderContent()}
        </Col>
      </Row>
      
      <Divider />
      
      <Title level={4}>多用户连接说明</Title>
      <Paragraph>
        此平台支持多用户独立连接WhatsApp。每个用户都有专属的连接会话和二维码，
        确保数据隔离和安全性。
      </Paragraph>
      
      <Title level={5}>注意事项：</Title>
      <Paragraph>
        <ul>
          <li>每个用户只能连接一个WhatsApp账号</li>
          <li>二维码是用户专属的，请勿分享给他人</li>
          <li>您的手机需要保持网络连接，以确保消息同步</li>
          <li>出于安全考虑，空闲时间过长可能会自动断开连接</li>
          <li>管理员可以监控所有用户的连接状态和活动</li>
        </ul>
      </Paragraph>
    </Card>
  );
};

export default WhatsAppConnect; 